package vn.com.ltv.lo.common;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.net.ConnectivityManager;
import android.os.Build;
import android.os.Environment;
import android.provider.Settings;
import android.util.DisplayMetrics;
import android.util.Log;

public final class FileManager {

	public final static int TAB_NORMAL = 0;
	public final static int TAB_LARGE = 1;
	public final static int TAB_SMALL = 2;
	public final static int TAB_XLARGE = 3;
	private FileManager() {
		// Do nothing
	}

	public static String getRealUrl(String stringUrl) {
		String returnStringUrl = new String(stringUrl);
		URL url;
		HttpURLConnection httpURLConnection;
		while (true) {
			returnStringUrl = returnStringUrl.replace("%20", " ");
			try {
				url = new URL(returnStringUrl);
			} catch (MalformedURLException e) {
				e.printStackTrace();
				return null;
			}   
			try {
				httpURLConnection = (HttpURLConnection) url.openConnection();
				// httpURLConnection.setReadTimeout(500);
			} catch (IOException e) {
				e.printStackTrace();
				return null;
			}
			httpURLConnection.setInstanceFollowRedirects(false);
			String headerField = httpURLConnection.getHeaderField("Location");
			if (headerField != null) {
				if (!headerField.trim().equals("")) {
					returnStringUrl = headerField;
				} else {
					break;
				}
			} else {
				break;
			}
		}
		Log.d("returnRealUrl", returnStringUrl);
		return returnStringUrl;
	}

	public static File[] getFilesInFolder(String path) {
		try {
			File file = new File(path);
			if (file.exists()) {
				if (file.isDirectory()) {
					return file.listFiles();
				} else {
					return null;
				}
			} else {
				return null;
			}
		} catch (Exception e) {
			return null;
		}
	}

	public static boolean fileExists(String path) {
		try {
			File file = new File(path);
			if (file.exists()) {
				return true;
			} else {
				return false;
			}
		} catch (Exception e) {
			return false;
		}
	}

	public static boolean folderExists(String path) {
		try {
			File file = new File(path);
			if (file.exists()) {
				if (file.isDirectory()) {
					return true;
				} else {
					return false;
				}
			} else {
				return false;
			}
		} catch (Exception e) {
			return false;
		}
	}

	public static boolean createFolder(String path) {
		try {
			File file = new File(path);
			if (file.exists()) {
				if (file.isDirectory()) {
					return true;
				} else {
					return false;
				}
			} else {
				return file.mkdirs();
			}
		} catch (Exception e) {
			return false;
		}
	}

	public static String getFileNameFromPath(String path) {
		String fileName = "";
		String realPath = getRealUrl(path);
		int lastIndexOfSlash = realPath.lastIndexOf('/');
		if (lastIndexOfSlash >= 0) {
			String tmp = realPath.substring(lastIndexOfSlash + 1);
			if (tmp.indexOf("-") >= 0) {
				fileName = tmp.substring(0, tmp.indexOf("-")).trim();
				Log.d("file name", "  " + fileName);
			} else {
				if (tmp.indexOf("_") >= 0) {
					fileName = tmp.substring(0, tmp.indexOf("_")).trim();
					Log.d("file name", "  " + fileName);
				}
			}
		} else {
			fileName = "";
		}
		return fileName;
	}

	public static String getArtistFromPath(String path) {
		String artist = "unknow";
		String realPath = getRealUrl(path);
		Log.d("real", "  " + realPath);
		int lastIndexOfSlash = realPath.lastIndexOf('/');
		if (lastIndexOfSlash >= 0) {
			String tmp = realPath.substring(lastIndexOfSlash + 1);
			if (tmp.indexOf("-") >= 0) {
				artist = tmp.substring(tmp.indexOf("-") + 1, tmp.indexOf("."))
						.trim();
				Log.d("artist", "  " + artist);
			} else {
				if (tmp.indexOf("_") >= 0) {
					artist = tmp.substring(tmp.indexOf("_") + 1,
							tmp.indexOf(".")).trim();
					Log.d("artist", "  " + artist);
				}
			}
		}
		return artist;
	}

	public static boolean deleteFileAndFolder(String path) {
		try {
			File file = new File(path);
			return deleteFileAndFolder(file);
		} catch (Exception e) {
			return false;
		}
	}

	public static boolean deleteFileAndFolder(File file) {
		if (file.isDirectory()) {
			File[] childrens = file.listFiles();
			for (int i = 0; i < childrens.length; i++) {
				if (!deleteFileAndFolder(childrens[i])) {
					return false;
				}
			}
		}

		return file.delete();
	}

	public static boolean changeFileAndFolder(String path, String newPath) {
		try {
			File file = new File(path);
			File newFile = new File(newPath);
			if (file.exists() ) {
				Log.d("move", "xong");
				return file.renameTo(newFile);
			} else {
				return false;
			}
		} catch (Exception e) {
			return false;
		}
	}

	public static String getFileNameFromContentDisposition(String contentDisposition, String page) {
		Log.d("contentDisposition", contentDisposition);
		String fileName = "";
		if (page.contains("nhacvui")) {
			if (contentDisposition.contains("/")) {
				int firstIndexOfDoubleQuote = contentDisposition.lastIndexOf('/');
				if (firstIndexOfDoubleQuote >= 0) {
					if (contentDisposition.contains(".")) {
						int lastIndexOfDoubleQuote = contentDisposition.lastIndexOf('.');
						String tmp = contentDisposition.substring(
								firstIndexOfDoubleQuote + 1, lastIndexOfDoubleQuote);
						if (tmp.contains("%20")) {
							tmp = tmp.replace("%20", " ");
						}
						fileName = tmp;
					}else{
						fileName = contentDisposition.substring(firstIndexOfDoubleQuote,contentDisposition.length()-1);
					}
					
				} else {
					fileName = System.currentTimeMillis() + "";
				}
			}else{
				fileName = System.currentTimeMillis() + "";
			}
			
		}else if (page.contains("keeng")) {
			int firstIndexOfDoubleQuote = contentDisposition.indexOf('_');
			if (firstIndexOfDoubleQuote >= 0) {
				int point = contentDisposition.lastIndexOf('.');
				fileName = contentDisposition.substring(firstIndexOfDoubleQuote+1, point);
				fileName = fileName.replace("_", " ");
			} else {
				fileName = System.currentTimeMillis() + "";
			}
		}else{
			fileName = System.currentTimeMillis() + "";
		}
		
		return fileName;
	}

	public static String getPathFromString(String s, Character c) {
		String address = "";
		int p = s.indexOf(c);
		address = s.substring(p);
		return address;

	}

	public static int getCountFiles(File file) {
		int count = 0;
		if (file.isDirectory()) {
			File[] childrens = file.listFiles();
			for (int i = 0; i < childrens.length; i++) {
				count += getCountFiles(childrens[i]);
			}
		} else {
			count++;
		}
		return count;
	}

	public static boolean copyFile(String sourceLocation, String destLocation) {
		try {
			File sd = Environment.getExternalStorageDirectory();
			if (sd.canWrite()) {
				File source = new File(sourceLocation);
				File dest = new File(destLocation);
				if (!dest.exists()) {
					dest.createNewFile();
				}
				if (source.exists()) {
					InputStream src = new FileInputStream(source);
					OutputStream dst = new FileOutputStream(dest);
					// Copy the bits from instream to outstream
					byte[] buf = new byte[1024];
					int len;
					while ((len = src.read(buf)) > 0) {
						dst.write(buf, 0, len);
					}
					src.close();
					dst.close();
				}
			}
			return true;
		} catch (Exception ex) {
			ex.printStackTrace();
			return false;
		}
	}

	public static String sub100String(String str){
		if (str.length() > 100) {
			String temp = str.substring(100,str.length());
			str = str.substring(0, 100);
			if (str.contains(" ")) {
				int space = temp.indexOf(" ");
				if (space > 0) {
					temp = temp.substring(0,space);
				}
				
			}
			
			str = str + temp +"...";
		}
		return str;
	}
	
	/**  
	 * Determine if the device is a tablet (i.e. it has a large screen).
	 * 
	 * @param context
	 *            The calling context.
	 */
	public static boolean isTablet(Context context) {
		return (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE;
	}

	/**
	 * Get the current Android API level.
	 */
	public static int getSdkVersion() {
		return Build.VERSION.SDK_INT;
	}

	/**
	 * Determine if the device is running API level 8 or higher.
	 */
	public static boolean isFroyo() {
		return getSdkVersion() >= Build.VERSION_CODES.FROYO;
	}

	/**
	 * Determine if the device is running API level 11 or higher.
	 */
	public static boolean isHoneycomb() {
		return getSdkVersion() >= Build.VERSION_CODES.HONEYCOMB;
	}

	/**
	 * Determine if the device is a HoneyComb tablet.
	 * 
	 * @param context
	 *            The calling context.
	 */
	public static boolean isHoneycombTablet(Context context) {
		return isHoneycomb() && isTablet(context);
	}
	
	public static String deviceID(Context context){
		return Settings.Secure.getString(context.getContentResolver(),Settings.Secure.ANDROID_ID);
	}
	
	
	public static boolean isNetworkAvailable(Context ctx) {
		 
	    ConnectivityManager connMgr = (ConnectivityManager)ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
	 
	    if(connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected() ||
	        connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnected()){
	            return true;
	    }
	 
	    return false;
	 }
	
	
	public static int getTabAndroid(Context context){
		int idTab = 0;
		DisplayMetrics metrics = new DisplayMetrics();
		((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(metrics);
		int widthPixels = metrics.widthPixels;
		int heightPixels = metrics.heightPixels;

		float scaleFactor = metrics.density;
		float widthDp = widthPixels / scaleFactor;
		float heightDp = heightPixels / scaleFactor;
		float smallestWidth = Math.min(widthDp, heightDp);

		if (smallestWidth > 600) {
			idTab = TAB_LARGE;
		} 
		else if (smallestWidth > 720) {
			idTab = TAB_XLARGE;
		}else{
			idTab = TAB_NORMAL;
		}
		return idTab;
	}
	
	
	
	
}
